package com.lambkit.module.upms;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.lambkit.auth.service.AuthDataService;
import com.lambkit.auth.service.AuthHttpService;
import com.lambkit.core.Lambkit;
import com.lambkit.core.http.IRequest;
import com.lambkit.module.upms.auth.service.UpmsDataService;
import com.lambkit.module.upms.auth.service.UpmsHttpService;

import java.util.Map;

/**
 * @author yangyong(孤竹行)
 */
public class Upms {
    private static Map<String, UpmsKernel> upmsKernelMap;
    private static String defaultName = null;
    public static void regist(String name, UpmsKernel upmsKernel) {
        if(upmsKernelMap ==null) {
            upmsKernelMap = MapUtil.newConcurrentHashMap();
        }
        upmsKernelMap.put(name, upmsKernel);
        if(StrUtil.isBlank(defaultName)) {
            defaultName = name;
        }
    }
    public static UpmsKernel use() {
        if(upmsKernelMap ==null || StrUtil.isBlank(defaultName)) {
            return null;
        }
        return upmsKernelMap.get(defaultName);
    }
    public static UpmsKernel use(String name) {
        if(upmsKernelMap ==null) {
            return null;
        }
        name = StrUtil.isBlank(name) ? defaultName : name;
        return upmsKernelMap.get(name);
    }

    public static UpmsKernel use(IRequest request) {
        if(upmsKernelMap ==null || StrUtil.isBlank(defaultName)) {
            return null;
        }
        String name = request.getHeader("upms");
        if(StrUtil.isBlank(name)) {
            name = request.getParameter("upms");
        }
        name = StrUtil.isBlank(name) ? defaultName : name;
        return upmsKernelMap.get(name);
    }

    public static void clearCachedAuth(String username) {
        for (UpmsKernel upmsKernel : upmsKernelMap.values()) {
            upmsKernel.getAuthKernelService().clearCachedAuth(username);
        }
    }

    public static UpmsApiService getApiService() {
        return Lambkit.get(UpmsApiService.class);
    }

    public static AuthDataService getAuthDataService() {
        return Lambkit.get(AuthDataService.class, UpmsDataService.class);
    }

    public static AuthHttpService getHttpService() {
        return Lambkit.get(AuthHttpService.class, UpmsHttpService.class);
    }
}
